using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Collections.Generic;

namespace Wicresoft.OmsClient
{
    class Initialization
    {
        Office.CommandBar newToolBar;
        Office.CommandBarButton btnSyncsetting;
        Office.CommandBarButton btnGreen;
        Office.CommandBarButton btnGray;
        Office.CommandBarButton btnRed;
        Outlook.Explorers selectExplorers;

        frmSetting frmsetting;

        ReminderSync rs;
        StateChecker sc;
        ContactsSync cs;

        Outlook._Application app;
        ThisAddIn tai;

        private global::System.Object missing = global::System.Type.Missing;

        private Initialization()
        { }

        private static Initialization ini;

        public static Initialization Instance
        {
            get 
            {
                if (ini == null)
                    ini = new Initialization();
                return ini; 
            }
        }

        public void Start(Outlook._Application _app, ThisAddIn _tai, string url)
        {
            try
            {                
                app = _app;
                tai = _tai;
                Logger.Info("Online, " + SysInfo);


                SyncConfigManage.SyncInterval = 60;
                if (SyncConfigManage.ProviderUrl == "")
                    SyncConfigManage.ProviderUrl = url;                
                if (SyncConfigManage.EnableCalendarSync == "")
                    SyncConfigManage.EnableCalendarSync = "true";
                if (SyncConfigManage.EnableContactSync == "")
                    SyncConfigManage.EnableContactSync = "true";

                selectExplorers = app.Explorers;
                selectExplorers.NewExplorer += new Outlook.ExplorersEvents_NewExplorerEventHandler(newExplorer_Event);
                AddToolbar();

                StateLight.Buttons = new cbbtnButtons(this.GetCommandBarButtonInstance);
                StateLight.Gray();

                sc = new StateChecker();
                sc.StartService();  

                ReminderGetter.Grfo = new GetReminderFromOutlook(this.GetReminderInstances);
                rs = new ReminderSync();
                rs.StartService();

                ContactsService.Contacts = new GetContactsFromOutlook(this.GetContacts);
                ContactsService.App = new GetApplicationInstance(this.GetAppInstance);
                cs = new ContactsSync();
                cs.StartService();                

                 
            }
            catch (Exception ex)
            {
                Logger.Exception("Initialization.Start", ex);
            }
           
        }

        public void Shutdown()
        {
            try
            {
                this.rs.StopService();
                this.sc.StopService();
                this.cs.StopService();
                Logger.Info("Offline " + SysInfo);
            }
            catch (Exception ex)
            {
                Logger.Exception("Initialization.Shutdown", ex);
            }
        }

        private string SysInfo
        {
            get
            {
                try
                {

                    string sysinfo = "Outlook Version: " + app.Version + ", ";
                    sysinfo += "Outlook Language: " + app.LanguageSettings.get_LanguageID(Office.MsoAppLanguageID.msoLanguageIDUI) + ", ";
                    sysinfo += "User Locale: " + System.Windows.Forms.Application.CurrentCulture.DisplayName + ", ";
                    // sysinfo += "System Locale: " + Thread.CurrentThread.CurrentCulture.DisplayName + ", ";
                    sysinfo += Environment.OSVersion.VersionString + ",";
                    sysinfo += "Current WinUser: " + Environment.UserName + ", ";
                    sysinfo += "Current Domain: " + Environment.UserDomainName;
                    return sysinfo;
                }
                catch(Exception ex)
                {
                    Logger.Exception("Initialization.SysInfo", ex);
                    return "An exception occurred when getting SysInfo";
                }
            }
        }

        private void newExplorer_Event(Outlook.Explorer new_Explorer)
        {
            try
            {
                ((Outlook._Explorer)new_Explorer).Activate();
                newToolBar = null;
                AddToolbar();
            }
            catch (Exception ex)
            {
                Logger.Exception("Initialization.newExplorer_Event", ex);
            }

        }

        private void AddToolbar()
        {
            try
            {
                if (newToolBar == null)
                {
                    Office.CommandBars cmdBars = app.ActiveExplorer().CommandBars;
                    newToolBar = cmdBars.Add("SMS Plugin Settings", Office.MsoBarPosition.msoBarTop, false, true);
                    newToolBar.Visible = true;
                }

                Office.CommandBarButton cbbred = (Office.CommandBarButton)newToolBar.Controls.Add(1, missing, missing, missing, missing);
                cbbred.Caption = "You are unauthorized";
                cbbred.Style = Microsoft.Office.Core.MsoButtonStyle.msoButtonIcon;
                cbbred.Picture = ConvertImage.Convert(Properties.Resources.Red);
                if (this.btnRed == null)
                {
                    this.btnRed = cbbred;
                }

                Office.CommandBarButton cbbgray = (Office.CommandBarButton)newToolBar.Controls.Add(1, missing, missing, missing, missing);
                cbbgray.Caption = "Service unavailable";
                cbbgray.Style = Microsoft.Office.Core.MsoButtonStyle.msoButtonIcon;
                cbbgray.Picture = ConvertImage.Convert(Properties.Resources.Gray);
                if (this.btnGray == null)
                {
                    this.btnGray = cbbgray;
                }

                Office.CommandBarButton cbbgreen = (Office.CommandBarButton)newToolBar.Controls.Add(1, missing, missing, missing, missing);
                cbbgreen.Caption = "Service available";
                cbbgreen.Style = Microsoft.Office.Core.MsoButtonStyle.msoButtonIcon;
                cbbgreen.Picture = ConvertImage.Convert(Properties.Resources.Green);
                if (this.btnGreen == null)
                {
                    this.btnGreen = cbbgreen;
                }

                Office.CommandBarButton syncsetting = (Office.CommandBarButton)newToolBar.Controls.Add(1, missing, missing, missing, missing);
                syncsetting.Caption = "Settings";
                syncsetting.TooltipText = "Configurate Outlook SMS Plugin";
                syncsetting.Tag = "Setting";
                if (this.btnSyncsetting == null)
                {
                    this.btnSyncsetting = syncsetting;
                    btnSyncsetting.Click += new Office._CommandBarButtonEvents_ClickEventHandler(ButtonClick);
                }

            }
            catch (Exception ex)
            {
                Logger.Exception("Initialization.AddToolbar ", ex);
            }
        }

        private void ButtonClick(Office.CommandBarButton ctrl, ref bool cancel)
        {
            try
            {
                if (frmsetting == null)
                    frmsetting = new frmSetting();
                frmsetting.ShowWindow();
            }
            catch (Exception ex)
            {
                Logger.Exception("Initialization.ButtonClick", ex);
            }

        }


       
        private Outlook.Reminders GetReminderInstances()
        {
            try
            {
                return app.Reminders;
            }
            catch (Exception ex)
            {
                Logger.Exception("Initialization.GetReminderInstances", ex);
                return null;
            }

        }

        private Office.CommandBarButton[] GetCommandBarButtonInstance()
        {
            try
            {
                Office.CommandBarButton[] btnarray = new Microsoft.Office.Core.CommandBarButton[] { this.btnGray, this.btnGreen, this.btnRed };
                foreach (Office.CommandBarButton item in btnarray)
                {
                    item.Visible = false;
                }
                return btnarray;
            }
            catch (Exception ex)
            {
                Logger.Exception("Initialization.GetReminderInstances", ex);
                return null;
            }
        }

        private Outlook.ContactItem[] GetContacts()
        {
            try
            {
                Outlook.MAPIFolder contactFolder = app.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
                Outlook.Items items = contactFolder.Items;
                List<Outlook.ContactItem> list = new List<Outlook.ContactItem>();
                if (items != null)
                {
                    foreach (object var in items)
                    {
                        Outlook.ContactItem item = (Outlook.ContactItem)var;
                        list.Add(item);
                    }
                }
                return list.ToArray();
            }
            catch (Exception ex)
            {
                Logger.Exception("Initialization.GetContacts ", ex);
                return null;
            }
        }

        private Outlook._Application GetAppInstance()
        {
            try
            {
                return app;
            }
            catch (Exception ex)
            {
                Logger.Exception("Initialization.GetReminderInstances", ex);
                return null;
            }
        }
    }
}
